# -*- coding:utf-8 -*-
from rest_framework.viewsets import ModelViewSet

from Apps.UITest.filters.uiCaseFilter import UiCaseFilter
from Apps.UITest.ser.UiCaseLog import uiCaseLogSer, runUiCaseSer
from Apps.UITest.ser.UiCaseSer import CaseSer
from Apps.UITest.models import uiCase
from rest_framework.views import APIView

from Apps.UITest.uiSelenium.runner import Runner
from Apps.common.fileUp.file import postFileSave
import logging, random
from captcha.conf.settings import settings
from Apps.UITest.models import uiCaseLog

from Apps.common.response import SuccessResponse
from Apps.util.request_util import setCreateUser
from django_redis import get_redis_connection

redis_conn = get_redis_connection("default")

logger = logging.getLogger('django')


class UiCaseView(ModelViewSet):
    serializer_class = CaseSer
    queryset = uiCase.objects.filter(is_delete=0).all()
    filter_class = UiCaseFilter

    def create(self, request, *args, **kwargs):
        request = setCreateUser(request)

        logger.info(request.data["case_url"])
        path = str(settings.BASE_DIR) + "/" + request.data["case_url"]
        logger.info(path)

        with open(path, "r") as f:
            request.data["case_data"] = f.read()

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return SuccessResponse("新建成功")


class saveCaseFileView(APIView):
    """
    保存上传的文件
    """
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        path = postFileSave(request, "uiCase")
        logger.info(path)
        return SuccessResponse(path)


class DeleteUiCaseView(APIView):
    def post(self, request, *args, **kwargs):
        idList = request.data["ids"]
        uiCase.objects.filter(id__in=idList).delete()
        return SuccessResponse("删除成功")


class runUiCaseView(APIView):
    def post(self, request, *args, **kwargs):
        caseId = request.data["id"]
        logger.info(caseId)
        caseInstance = uiCase.objects.get(id=caseId)

        # caseLog = uiCaseLog(creator=request.user.id,modifier=request.user.id,
        #                     status=1,
        #                     case=caseInstance,run_case_data=caseInstance.case_data)
        # caseLogInstance = caseLog.save()
        caseLog = {
            "creator": request.user.id,
            "modifier": request.user.id,
            "status": 1,
            "case": caseInstance.id,
            "run_case_data": caseInstance.case_data
        }
        ser = runUiCaseSer(data=caseLog)
        ser.is_valid(raise_exception=True)
        caseLogInstance = ser.save()
        logger.info(caseLogInstance.id)
        # 放入redis队列中
        redis_conn.rpush("UiTestList", str(caseLogInstance.id))

        # Runner(caseInstance.case_data,caseLogInstance)

        return SuccessResponse("已添加到运行队列")
